<template>
  <div class="order-container">
    <!-- 顶部导航 -->
    <el-header class="order-header">
      <div class="header-title">我的订单</div>
    </el-header>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <span>加载中...</span>
    </div>

    <!-- 空状态 -->
    <div v-else-if="orders.length === 0" class="empty-container">
      <el-icon><DocumentDelete /></el-icon>
      <p>暂无订单</p>
    </div>

    <!-- 订单列表 -->
    <div v-else class="order-list">
      <div
          v-for="order in orders"
          :key="order.orderid"
          class="order-item"
          @click="goToOrderDetail(order.orderid)"
      >
        <!-- 商家信息 -->
        <div class="merchant-info">
          <img :src="getImageUrl(order.orderDetaildDto.merchantAvatar)" class="merchant-avatar">
          <span class="merchant-name">{{ order.orderDetaildDto.merchantName }}</span>
          <el-tag :type="getStatusTagType(order.orderDetaildDto.status)" size="small" class="status-tag">
            {{ getStatusText(order.orderDetaildDto.status) }}
          </el-tag>
        </div>

        <!-- 商品简要信息 -->
        <div class="item-preview">
          <span class="item-names">
            {{ getItemNames(order.orderDetaildDto.items) }}
          </span>
          <span class="item-count">共{{ getItemCount(order.orderDetaildDto.items) }}件</span>
        </div>

        <!-- 订单金额信息 -->
        <div class="order-summary">
          <div class="summary-row">
            <span>商品总价</span>
            <span>¥{{ (order.orderDetaildDto.totalPrice - order.orderDetaildDto.deliveryfee).toFixed(2) }}</span>
          </div>
          <div class="summary-row">
            <span>配送费</span>
            <span>¥{{ order.orderDetaildDto.deliveryfee.toFixed(2) }}</span>
          </div>
          <div class="summary-row total">
            <span>实付款</span>
            <span class="total-price">¥{{ order.orderDetaildDto.totalPrice.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 订单编号和时间 -->
        <div class="order-meta">
          <span class="order-no">订单编号: {{ order.orderDetaildDto.orderNo }}</span>
          <span class="order-time">{{ formatTime(order.orderDetaildDto.createTime) }}</span>
        </div>
      </div>
    </div>
    <FooterGuide />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  Loading,
  DocumentDelete
} from '@element-plus/icons-vue'
import axios from 'axios'
import { API_BASE_URL } from '@/config'
import { useCookies } from 'vue3-cookies'
import { ElMessage } from 'element-plus'
import FooterGuide from "@/components/FooterGuide/FooterGuide.vue";

const { cookies } = useCookies()
const router = useRouter()

// 订单数据
const orders = ref([])
const loading = ref(true)

// 获取订单列表
const fetchOrders = async () => {
  try {
    const userId = cookies.get('userId')
    if (!userId) {
      ElMessage.error('用户未登录')
      return
    }

    const response = await axios.post(`${API_BASE_URL}/order/getorders`, null, {
      params: { userid: userId }
    })
    orders.value = response.data
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error('Error fetching orders:', error)
  } finally {
    loading.value = false
  }
}

// 获取图片完整URL
const getImageUrl = (path) => {
  if (!path) return ''
  return `${import.meta.env.VITE_API_BASE_URL}${path}`
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '--'
  return new Date(timeStr).toLocaleString()
}

// 获取商品名称拼接
const getItemNames = (items) => {
  const nameMap = {}
  items.forEach(item => {
    if (nameMap[item.name]) {
      nameMap[item.name] += item.quantity
    } else {
      nameMap[item.name] = item.quantity
    }
  })

  return Object.entries(nameMap)
      .map(([name, count]) => `${name}×${count}`)
      .join('，')
}

// 获取商品总数量
const getItemCount = (items) => {
  return items.reduce((total, item) => total + item.quantity, 0)
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已取消',
    1: '待支付',
    2: '已支付',
    3: '配送中',
    4: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: '',
    4: 'success'
  }
  return typeMap[status] || 'info'
}

// 跳转到订单详情
const goToOrderDetail = (orderId) => {
  router.push(`/order/detail/${orderId}`)
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-container {
  padding-bottom: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.order-header {
  position: sticky;
  top: 0;
  z-index: 10;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  height: 50px;
  border-bottom: 1px solid #eee;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-icon {
  font-size: 40px;
  margin-bottom: 10px;
  animation: rotating 2s linear infinite;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #999;
}

.empty-container .el-icon {
  font-size: 60px;
  margin-bottom: 15px;
}

.empty-container p {
  font-size: 16px;
  margin-top: 10px;
}

.order-list {
  padding: 10px;
}

.order-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s;
}

.order-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.merchant-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  position: relative;
}

.merchant-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
  object-fit: cover;
}

.merchant-name {
  font-size: 16px;
  font-weight: bold;
  flex: 1;
}

.status-tag {
  position: absolute;
  right: 0;
}

.item-preview {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #eee;
}

.item-names {
  flex: 1;
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 10px;
}

.item-count {
  font-size: 14px;
  color: #999;
}

.order-summary {
  margin-bottom: 12px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #666;
  margin-bottom: 5px;
}

.summary-row.total {
  margin-top: 8px;
  font-weight: bold;
  color: #333;
}

.total-price {
  color: #ff5339;
  font-size: 15px;
}

.order-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>